$(function() {
    // Login
    if(localStorage.username)
        $("#loginForm").html(localStorage.username + ' <a href="CMS_login.jsp">CMS</a> <a id="logout" class="btn btn-primary">Logout</a>');
    else
        $("#loginForm").html('<div class="alert"></div>\n'
                + '<input type="text" id="username" placeholder="Username" />\n'
                + '<input type="password" id="password" placeholder="Password" />\n'
                + '<input type="submit" id="signin" value="Sign In" class="btn btn-primary" />'
                + '<input type="button" id="signup" value="Sign Up" class="btn btn-highlight" />');
    $("#loginForm").submit(function(e) {
        e.preventDefault();
        $.post("Login", {
                user_id: $("#loginForm #username").val(),
                user_pwd: $("#loginForm #password").val()
        },
        function(data) {
            if(data.success) {
                localStorage.username = $("#username").val();
                $("#loginForm").html($("#username").val() + ' <a href="CMS_login.jsp">CMS</a> <a id="logout" class="btn btn-primary">Logout</a>');
            }
            else
                $("#loginForm .alert").html("Check your username and password again!");
        }, "json");
    });
    $("#logout").click(function(e) {
        e.preventDefault();
        localStorage.username = "";
        $("#loginForm").html('<div class="alert"></div>\n'
                + '<input type="text" id="username" placeholder="Username" />\n'
                + '<input type="password" id="password" placeholder="Password" />\n'
                + '<input type="submit" id="signin" value="Sign In" class="btn btn-primary" />'
                + '<input type="button" id="signup" value="Sign Up" class="btn btn-highlight" />');
    });
    
    // Register
    if($("#signup").get(0))
        $("#signup").colorbox({iframe: true, width: "70%", height: "80%", href: "register.html"});
    var DOM = ["userid", "password1", "password2", "email", "firstname", "lastname", "gender", "DOB", "flat", "building_block", "district", "region"];
    var emailRe = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
    var dateRe = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
    for(i = 0; i < DOM.length; i++) {
        $("label[for='" + DOM[i] + "']").addClass("must");
        $("#" + DOM[i]).focusout(function() {
            if($(this).val() == "") {
                $(this).addClass("alert");
                if(!$(this).prev().children("span.alert").get(0))
                    $(this).prev().append("<span class='alert'>This field cannot be empty</span>");
                else
                    $(this).prev().children("span.alert").html("This field cannot be empty");
            } else if($(this).attr("id") == "password2" && $(this).val() != $("#password1").val()) {
                if(!$(this).prev().children("span.alert").get(0))
                    $(this).prev().append("<span class='alert'>Password is not the same</span>");
                else
                    $(this).prev().children("span.alert").html("Password is not the same");
            } else if($(this).attr("id") == "email" && !emailRe.test($(this).val())) {
                if(!$(this).prev().children("span.alert").get(0))
                    $(this).prev().append("<span class='alert'>Please follow the email format</span>");
                else
                    $(this).prev().children("span.alert").html("Please follow the email format");
            } else if($(this).attr("id") == "DOB" && !dateRe.test($(this).val())) {
                if(!$(this).prev().children("span.alert").get(0))
                    $(this).prev().append("<span class='alert'>Please follow the date format</span>");
                else
                    $(this).prev().children("span.alert").html("Please follow the date format");
            } else {
                $(this).removeClass("alert");
                $(this).prev().children("span.alert").remove();
            }
        });
    }
    ckForm = function() {
        var error = 0;
        for(i = 0; i < DOM.length; i++) {
            if($("#" + DOM[i]).val() == "") {
                $("#" + DOM[i]).addClass("alert");
                if(!$("label[for='" + DOM[i] + "'] span.alert").get(0))
                    $("label[for='" + DOM[i] + "']").append("<span class='alert'>This field cannot be empty</span>");
                else
                    $("label[for='" + DOM[i] + "'] span.alert").html("This field cannot be empty");
                error = 1;
            } else if($("#" + DOM[i]).attr("id") == "password2" && $("#" + DOM[i]).val() != $("#password1").val()) {
                if(!$("label[for='" + DOM[i] + "'] span.alert").get(0))
                    $("label[for='" + DOM[i] + "']").append("<span class='alert'>Password is not the same</span>");
                else
                    $("label[for='" + DOM[i] + "'] span.alert").html("Password is not the same");
                error = 1;
            } else if($("#" + DOM[i]).attr("id") == "email" && !emailRe.test($("#" + DOM[i]).val())) {
                if(!$("label[for='" + DOM[i] + "'] span.alert").get(0))
                    $("label[for='" + DOM[i] + "']").append("<span class='alert'>Please follow the email format</span>");
                else
                    $("label[for='" + DOM[i] + "'] span.alert").html("Please follow the email format");
                error = 1;
            } else if($("#" + DOM[i]).attr("id") == "DOB" && !dateRe.test($("#" + DOM[i]).val())) {
                if(!$("label[for='" + DOM[i] + "'] span.alert").get(0))
                    $("label[for='" + DOM[i] + "']").append("<span class='alert'>Please follow the date format</span>");
                else
                    $("label[for='" + DOM[i] + "'] span.alert").html("Please follow the date format");
                error = 1;
            } else {
                $("#" + DOM[i]).removeClass("alert");
                $("label[for='" + DOM[i] + "'] span.alert").remove();
            }
        }
        return (error == 0) ? true : false;
    };
    $("#registerForm").submit(function(e) {
        e.preventDefault();
        if(ckForm()) {
            $.post("Register", {
                user_id: $("#userid").val(),
                user_pwd1: $("#password1").val(),
                email: $("#email").val(),
                firstname: $("#firstname").val(),
                midname: $("#midname").val(),
                lastname: $("#lastname").val(),
                nickname: $("#nickname").val(),
                gender: $("#gender").val(),
                hometel: $("#hometel").val(),
                celltel: $("#celltel").val(),
                DOB: $("#DOB").val(),
                flat: $("#flat").val(),
                building_block: $("#building_block").val(),
                district: $("#district").val(),
                region: $("#region").val()
            },
            function(data) {
                var msg;
                switch(data.success) {
                    case 1:
                        msg = "Successful";
                    case Default:
                        msg = "Error, try again later";
                }
                $("body").fadeOut(300).html(msg).fadeIn(500);
                setTimeout(parent.$.fn.colorbox.close(), 1800);
            }, "json");
        }
    });
    
    // Homepage content
    var default_content = function() {
        $(".content .aux").hide().html("");
        $.get("Listing.jsp", function(data) {
            for(i = 0; i < data.length; i++) {
                $(".content .aux").append('<div class="product link' + i + '">'
                        + '<img src="img/' + data[i].id + '/cover.jpg" />'
                        + '<div class="detail">'
                        + '<p>Album Name: ' + data[i].name + '</p>'
                        + '<p>Price: $' + data[i].price + '</p>'
                        + '</div>'
                        + '</div>');
                $(".product.link" + i).colorbox({iframe: true, width: "80%", height: "90%", href: "detail.jsp?id=" + data[i].id});
            }
            $(".content .aux").fadeIn(500);
        }, "json");
    };

    // Navbar
    $(window).scroll(function(e) {
        if($(window).scrollTop() > 60)
            $("header > #floatWrapper").addClass("float");
        else if($(window).scrollTop() < 60)
            $("header > #floatWrapper").removeClass("float");
    });
    $("#statusBar #logo").click(function(e) {
        e.preventDefault();
        default_content();
    });
    $("nav #cart").click(function(e) {
        e.preventDefault();
        $(".content .aux").html('<div class="product">'
                + '<div class="remove">Remove</div>'
                + '<img width="300px" style="align:center;" src="img/x-men.JPG" />'
                + '<div class="detail">'
                + '<p>Album Name: Xmen</p>'
                + '<p>Price: $150</p>'
                + '</div>'
                + '</div>');
        $(".content .aux .remove").click(function(e) {
            $(this).parent(".product").remove();
        });
    });
    $("nav #checkout").click(function(e) {
        e.preventDefault();
        $(".content .aux").html('<iframe src="CMS_paymentMethod.jsp" width="100%" seamless="seamless"></iframe>');
    });
    $("nav #shop").click(function(e) {
        e.preventDefault();
        default_content();
    });
    default_content();
});
